#include "driver/rmt.h"

void setup_rmt_receiver() {
    rmt_config_t rmt_rx = {
        .channel = RMT_CHANNEL_0,
        .gpio_num = GPIO_NUM_4,
        .clk_div = 80,  // 80 MHz / 80 = 1 MHz (1μs 分辨率)
        .mem_block_num = 1,
        .rmt_mode = RMT_MODE_RX,
        .rx_config.filter_en = true,
        .rx_config.filter_ticks_thresh = 100, // 过滤短脉冲
        .rx_config.idle_threshold = 12000      // 12ms 空闲视为结束
    };
    rmt_config(&rmt_rx);
    rmt_driver_install(rmt_rx.channel, 1000, 0);
    
    // 启动接收
    rmt_get_ringbuf_handle(rmt_rx.channel, &ringbuf);
    rmt_rx_start(rmt_rx.channel, true);
    
    // 在任务中处理接收到的信号
    xTaskCreate(rmt_task, "rmt_task", 4096, NULL, 10, NULL);
}

void rmt_task(void *arg) {
    rmt_item32_t* items = NULL;
    size_t length = 0;
    while(1) {
        items = (rmt_item32_t*)xRingbufferReceive(ringbuf, &length, portMAX_DELAY);
        if (items) {
            // 解析电平变化和精确时间
            for (int i = 0; i < length / sizeof(rmt_item32_t); i++) {
                uint32_t duration = items[i].duration0; // 低电平时间
                uint32_t level = items[i].level0;       // 电平状态
            }
            vRingbufferReturnItem(ringbuf, items);
        }
    }
}